// 多数据库配置 - 支持PostgreSQL和MongoDB
import { MongoClient } from 'mongodb';

// MongoDB连接配置
const mongoConfig = {
  url: process.env.MONGO_URL || 'mongodb://localhost:27017',
  dbName: process.env.MONGO_DB_NAME || 'bike_wholesale',
  options: {
    maxPoolSize: parseInt(process.env.MONGO_MAX_POOL_SIZE) || 10,
    minPoolSize: parseInt(process.env.MONGO_MIN_POOL_SIZE) || 2,
    connectTimeoutMS: parseInt(process.env.MONGO_CONNECT_TIMEOUT) || 30000,
    socketTimeoutMS: parseInt(process.env.MONGO_SOCKET_TIMEOUT) || 45000,
    serverSelectionTimeoutMS: parseInt(process.env.MONGO_SERVER_SELECTION_TIMEOUT) || 30000,
    retryWrites: true,
    w: 'majority'
  }
};

// MongoDB客户端实例
let mongoClient = null;
let mongoDb = null;

// 初始化MongoDB连接
async function initMongoDB() {
  try {
    console.log('🔧 初始化MongoDB连接...');
    
    mongoClient = new MongoClient(mongoConfig.url, mongoConfig.options);
    await mongoClient.connect();
    
    mongoDb = mongoClient.db(mongoConfig.dbName);
    
    console.log('✅ MongoDB连接成功');
    console.log(`   数据库: ${mongoConfig.dbName}`);
    console.log(`   连接池大小: ${mongoConfig.options.maxPoolSize}`);
    
    // 创建索引
    await createMongoIndexes();
    
  } catch (error) {
    console.error('❌ MongoDB连接失败:', error);
    throw error;
  }
}

// 创建MongoDB索引
async function createMongoIndexes() {
  try {
    // 图库集合索引
    await mongoDb.collection('gallery').createIndexes([
      { key: { category: 1 } },
      { key: { usageType: 1 } },
      { key: { isActive: 1 } },
      { key: { sortOrder: 1 } },
      { key: { createdAt: -1 } },
      { key: { tags: 1 } },
      { key: { name: 'text', description: 'text', tags: 'text' } }
    ]);
    
    // 轮播图集合索引
    await mongoDb.collection('carousel').createIndexes([
      { key: { isActive: 1 } },
      { key: { sortOrder: 1 } },
      { key: { createdAt: -1 } }
    ]);
    
    // Logo集合索引
    await mongoDb.collection('logos').createIndexes([
      { key: { isActive: 1 } },
      { key: { usageType: 1 } },
      { key: { createdAt: -1 } }
    ]);
    
    // 产品图集合索引
    await mongoDb.collection('product_images').createIndexes([
      { key: { productId: 1 } },
      { key: { isActive: 1 } },
      { key: { sortOrder: 1 } },
      { key: { createdAt: -1 } }
    ]);
    
    // 博客图集合索引
    await mongoDb.collection('blog_images').createIndexes([
      { key: { blogId: 1 } },
      { key: { isActive: 1 } },
      { key: { sortOrder: 1 } },
      { key: { createdAt: -1 } }
    ]);
    
    console.log('✅ MongoDB索引创建完成');
  } catch (error) {
    console.error('❌ MongoDB索引创建失败:', error);
  }
}

// 获取MongoDB数据库实例
function getMongoDB() {
  if (!mongoDb) {
    throw new Error('MongoDB未初始化，请先调用initMongoDB()');
  }
  return mongoDb;
}

// 关闭MongoDB连接
async function closeMongoDB() {
  if (mongoClient) {
    await mongoClient.close();
    console.log('🔌 MongoDB连接已关闭');
  }
}

// 健康检查
async function checkMongoDBHealth() {
  try {
    if (!mongoDb) {
      return { status: 'disconnected', message: 'MongoDB未连接' };
    }
    
    await mongoDb.command({ ping: 1 });
    return { status: 'connected', message: 'MongoDB连接正常' };
  } catch (error) {
    return { status: 'error', message: `MongoDB连接异常: ${error.message}` };
  }
}

export {
  initMongoDB,
  getMongoDB,
  closeMongoDB,
  checkMongoDBHealth,
  mongoDb
};